import * as api from '@/services/checkSchedule';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Badge, Button, Collapse, Popconfirm, Space, Tag, } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import CheckReportForm from './CheckReportForm';
import CheckForm from './CheckForm';
import * as utils from '@/utils/utils';
import * as c from '@/services/consts';
import Countdown from 'antd/es/statistic/Countdown';
const { Panel } = Collapse;
import CheckScheduleLogStatusTag from '@/components/CheckScheduleLogStatusTag';
import dayjs from 'dayjs';
const dateFormat = 'YYYY-MM-DD';

const OrderList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const [formCheckReportVisible, setFormCheckReportVisible] =useState<boolean>(false);
  const [formCheckVisible, setFormCheckVisible] =useState<boolean>(false);

  const [countdownTicks, setCountdownTicks] = useState<number>(Date.now() + 60000,);  
  const [current, setCurrent] = useState<API.CheckSchedule | undefined>(undefined);

  
  const { getVpnGroupOptions } = useModel('useGlobalModel', (model) => ({
    // getSupplier: model.getSupplier,
    getVpnGroupOptions: model.getVpnGroupOptions,
  }));
  

  
  const handleCheckSubmit = () => {
    setFormCheckVisible(false);
    setCurrent(undefined);
    actionRef?.current?.reload();
  };

  const handleRemove = async (ver: string | undefined) => {
    const result = await api.remove({ver});
    if (result && result.success) {
      actionRef?.current?.clearSelected();
      actionRef?.current?.reload();
    }
  };

  const handleStatus = async (keys: any[], status : boolean) => {
    const result = await api.status({keys, status});
    if (result && result.success) {
      actionRef?.current?.clearSelected();
      actionRef?.current?.reload();
    }
  };

    
  const reload = () => {
    actionRef.current?.reload();
    setCountdownTicks(Date.now() + 60000);
  };

  let columns: ProColumns<API.CheckSchedule>[] = [
    {
      title: '版本',
      dataIndex: 'id',
      width: 350,
      sorter: true,
      render: (_, record) => {
        return (
          <>
          <div>
            <Tag color={record.status == true ? 'success' : 'error'}>{record.id}</Tag>
            {record.policy?.runEndStartTiming == true ? <span style={{color:'#999'}}>执行完后间隔 {record.interval} 分执行</span>
            : <span style={{color:'#999'}}>每间隔 {record.interval} 分执行</span>}
          </div>
          {record.policy?.checkPolicy?.status == true ? 
          <div>
            <Tag><span style={{color:'#999'}}>{c.getObjectText(c.CheckJobAllOptions, record.taskJob)}</span></Tag>
            <Tag><span style={{color:'#999'}}>{c.getObjectText(c.CheckTaskItemStatusOptions, record.taskCheckStatus)}</span></Tag>
            {record.taskCheckBlock ? <Tag><span style={{color:'#999'}}>检测被墙</span></Tag> : ''}
            {record.policy?.checkPolicy?.blockForSecondCheck == true ? <Tag><span style={{color:'#999'}}>初检被墙进行二检</span></Tag> : ''}
          </div> : ''}

          {record.policy?.changeIpPolicy?.status == true ? 
          <div>
            {record.policy?.changeIpPolicy?.checkIpBlacklist == true ? <Tag><span style={{color:'#999'}}>比对黑名单</span></Tag> : ''}
            {record.policy?.changeIpPolicy?.endRecheck == true ? <Tag><span style={{color:'#999'}}>更换后重检</span></Tag> : ''}
          </div> : ''}

          {/* <Tag color={utils.getTextRanColor(record.taskJob)}>{c.getObjectText(c.CheckJobAllOptions, record.taskJob)}</Tag>
          {record.taskMode ? <Tag color={utils.getTextRanColor(record.taskMode)}>{c.getObjectText(c.CheckModeOptions, record.taskMode)}</Tag> : ''} */}
          {record.createUser ? <div style={{color:'#aaa'}}>创建：{utils.formatDate(record.createTime)} / {record.createUser}</div> : ''}
          {record.updateUser ? <div style={{color:'#aaa'}}>更新：{utils.formatDate(record.updateTime)} / {record.updateUser}</div> : ''}
          </>
        );
      },
    },
    
    {
      title: '检测内容',
      dataIndex: 'instanceIds',
      search: false,
      sorter: true,
      render: (_, record) => {
        let txtColor = '';
        return <>
        
        <Collapse style={{marginBottom:10}} defaultActiveKey={['33']} ghost size='small'><Panel key="33" header={<>
        <span style={{color:'#D48806'}}><b>{record.name}</b></span>
          {record.remark ? <span style={{color:'#999'}}> {record.remark}</span> : ''}
          </>}>
        
        
        
        {record.lastPublish ? 
          <div style={{marginBottom:10}}>
          <div><b>最后执行：</b><Tag color={utils.getDayTextColor(record.lastPublish, record.interval)}>{utils.formatDate(record.lastPublish)}</Tag>{record.lastPublishId ? ` / ${record.lastPublishId}` : ''}
              【<span style={{color: record.lastPublishMessage?.indexOf("成功") == -1 ? 'red': ''}}>{record.lastPublishMessage}</span>】
          </div>
          <div>{record.status == true ? <><b>下次执行：</b>{utils.formatDate(utils.dateAdd(new Date(record.lastPublish) ?? new Date(), 'n', record.interval))}　</> : ''}
          执行信息：{record.logs?.map((val) =>{
            return <><CheckScheduleLogStatusTag status={val.status} />
              {val?.reports?.length ? <span style={{color: 'red'}}>【被墙：{val?.reports?.length}】</span> : ''}
            </>
          }) }
          </div>
          </div>
        : ''}
        
        <div style={{marginBottom:10}}>
        {record.checkServerGroups?.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>})}
        </div>
        {/* {record.templetNames && record.templetNames.length > 0 ? <div style={{marginBottom:10}}><h4>检测模板</h4>
          {record.templetNames.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''} */}

        {record.groupNames && record.groupNames.length > 0 ? <div style={{marginBottom:10}}><h4>检测分组</h4>
          {record.groupNames.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}

        {/* {record.instanceIds && record.instanceIds.length > 0 ? <div style={{marginBottom:10}}><h4>检测节点</h4>
          {record.instanceIds.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}

        {record.supplierIds && record.supplierIds.length > 0 ? <div style={{marginBottom:10}}><h4>服务器提供商</h4>
          {record.supplierIds.map((sid)=>{
          return <Tag color="blue">{getSupplier(sid)?.name}</Tag>
        })}</div> : ''}

        {record.customs && record.customs.length > 0 ? <div style={{marginBottom:10}}><h4>自定义检测</h4>
          {record.customs.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''} */}
        
        </Panel></Collapse>
        </>
      },
    },
    
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'single',
        allowClear: true,
        showSearch: true,
        options: c.CheckTaskStatusOptions,
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '分组',
      dataIndex: 'groupId',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'single',
        allowClear: true,
        showSearch: true,
        options: getVpnGroupOptions(undefined),
      },
    },

  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => {
        let cmps = [];
        
        if (hasRight('checkschedule_update')) {
          cmps.push(
            <a
              key="edit_group"
              onClick={(e) => {
                setFormCheckVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }
        if (hasRight('checkschedule_delete')) {
          cmps.push(
            <Popconfirm
              key="check_delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }


        if (hasRight('checkschedule_list')) {

          cmps.push(
            <a
              key="checkschedule_report"
              onClick={() => {
                setCurrent(record);
                setFormCheckReportVisible(true);
              }}
            >
              执行记录
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        search={{
          defaultCollapsed: false,
          span: 4,
        }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          if (hasRight('checkschedule_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create_checkschedule"
                onClick={() => {
                  setFormCheckVisible(true);
                  setCurrent(undefined);
                }}
              >
               新建
              </Button>
            ]);
          }

          toolbarDoms.push([
            <span>
            <Countdown
              title=""
              key="cdRefresh"
              value={countdownTicks}
              format="s"
              prefix=""
              suffix="秒后刷新"
              valueStyle={{
                fontSize: 14,
                color: 'gray',
              }}
              onFinish={reload}
            />
          </span>
          ]);

          return toolbarDoms;
        }}
        rowSelection={{
          defaultSelectedRowKeys: [],
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消
              </a>
            </span>
            

            <span>
              {hasRight('checkschedule_update') ?
                  <Popconfirm
                    key="check_delete"
                    title="确定要禁用吗?"
                    onConfirm={async () => {
                      await handleStatus(selectedRowKeys, false);
                    }}
                  >
                    <a>禁用</a>
                  </Popconfirm>
                : ''
              }
            </span>

            <span>
              {hasRight('checkschedule_update') ?
                  <Popconfirm
                    key="check_delete"
                    title="确定要启用吗?"
                    onConfirm={async () => {
                      await handleStatus(selectedRowKeys, true);
                    }}
                  >
                    <a>启用</a>
                  </Popconfirm>
                : ''
              }
            </span>
          </Space>
        )}
        columns={columns}
        pagination={{
          defaultPageSize: 50,
          pageSizeOptions: ['50', '100', '200'],
          hideOnSinglePage: true,
        }}
        request={api.list}
      />
      <CheckReportForm
        visible={formCheckReportVisible}
        current={current}
        onCancel={() => {
          setFormCheckReportVisible(false);
          setCurrent(undefined);
        }}
        // onCancelAndReload={() => {
        //   setFormCheckReportVisible(false);
        //   setCurrent(undefined);
        //   actionRef.current?.reload();
        // }}
      />
      <CheckForm
        visible={formCheckVisible}
        current={current}
        onCancel={() => {
          setFormCheckVisible(false);
          setCurrent(undefined);
        }}
        onSubmit={handleCheckSubmit}
      /> 
    </PageContainer>
  );
};

export default OrderList;
